<template>
  <div id="id">
    <Input v-model="value" placeholder="请输入手机号码" style="width: 200px;margin-right:20px;" />
    <Button type="primary" @click="addUser" style="margin-right:20px;">添加</Button>
    <Button type="primary" @click="Search">搜索</Button>
    <Table border :columns="columns7" :data="data6" style="margin-top:20px"></Table>
    <Modal v-model="modal1" :title="Title" @on-ok="ok" :ok-text="OnText">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="手机号码" prop="mobile">
          <Input v-model="formValidate.mobile" placeholder="请输入手机号码"></Input>
        </FormItem>
        <FormItem label="用户名" prop="realName">
          <Input v-model="formValidate.realName" placeholder="请输入用户名"></Input>
        </FormItem>
        <div v-if="isShowPaawd">
          <FormItem label="密码" prop="passwd">
            <Input type="password" v-model="formValidate.passwd" placeholder="请输入密码"></Input>
          </FormItem>
          <FormItem label="重复密码" prop="passwdCheck">
            <Input type="password" v-model="formValidate.passwdCheck" placeholder="请再次输入密码"></Input>
          </FormItem>
        </div>
        <FormItem label="角色">
          <Select v-model="model10" multiple style="width:260px">
            <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="头像">
          <Upload action="http://127.0.0.1:7001/api/upload" :default-file-list="defaultList" :on-exceeded-size="handleMaxSize" :on-remove="onRemove" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048">
            <Button icon="ios-cloud-upload-outline">头像上传</Button>
          </Upload>
        </FormItem>
      </Form>
    </Modal>
    <Page :total="Total" v-if="isShow" @on-change="OnChange"></Page>
    <!-- 展示的重置密码数据 -->
    <Modal v-model="modalPwd" title="修改密码" @on-ok="ResetPassword" ok-text="修改">
      <Form ref="formValidatePwd" :rules="ruleValidatePwd" :model="formValidatePwd" :label-width="80">
        <FormItem label="原密码" prop="oldPassword">
          <Input v-model="formValidatePwd.oldPassword" placeholder="请输入原密码"></Input>
        </FormItem>
        <FormItem label="新密码" prop="password">
          <Input v-model="formValidatePwd.password" placeholder="请输入新密码"></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  queryUser,
  addUserS,
  deleteUser,
  ChangeUser,
  ChangeUserPwd,
  removeImage
} from "@/api/admin/User";
import { QueryRole } from "@/api/admin/Role";
import config from "@/config";
export default {
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value !== this.formValidate.passwd) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.formValidate.passwdCheck !== "") {
          // 对第二个密码框单独验证
          this.$refs.formValidate.validateField("passwdCheck");
        }
        callback();
      }
    };
    const validateMobile = (rule, value, callback) => {
      let Raxg = /^[0-9]{11}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!Raxg.test(value)) {
        callback(new Error("输入的格式不正确"));
      }
      callback();
    };
    const validateRealName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      }
      callback();
    };
    return {
      baseUrl: process.env.BASE_URL, //引入文件的基础的路径
      value: "",
      defaultList: [],
      imgName: "",
      visible: false,
      UploadPicture: {},
      uploadList: [],
      modal1: false,
      Title: "添加用户",
      modalPwd: false,
      formValidate: {},
      cityList: [],
      isStatus: true,
      isShowPaawd: false,
      Total: 0,
      model10: [],
      OnText: "添加",
      isShow: false,
      ChangeValId: "",
      formValidatePwd: {
        passwd: "",
        oldPassword: ""
      },
      ruleValidatePwd: {
        oldPassword: [
          {
            required: true,
            message: "请输入原密码",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur"
          }
        ]
      },
      ruleValidate: {
        mobile: [
          {
            validator: validateMobile,
            trigger: "blur"
          }
        ],
        realName: [
          {
            validator: validateRealName,
            trigger: "blur"
          }
        ],
        passwd: [
          {
            validator: validatePass,
            trigger: "blur"
          }
        ],
        passwdCheck: [
          {
            validator: validatePassCheck,
            trigger: "blur"
          }
        ]
      },
      columns7: [
        {
          title: "用户名",
          key: "realName"
          // render: (h, params) => {
          //   return h('div', [
          //     h('Icon', {
          //       props: {
          //         type: 'person'
          //       }
          //     }),
          //     h('strong', params.row.name)
          //   ])
          // }
        },
        {
          title: "手机号码",
          key: "mobile"
        },
        {
          title: "创建时间",
          key: "createdAt"
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.show(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.ChangePassword(params.row);
                    }
                  }
                },
                "修改密码"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove(params);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data6: [
        {
          name: "John Brown",
          age: 18,
          address: "New York No. 1 Lake Park"
        },
        {
          name: "Jim Green",
          age: 24,
          address: "London No. 1 Lake Park"
        },
        {
          name: "Joe Black",
          age: 30,
          address: "Sydney No. 1 Lake Park"
        },
        {
          name: "Jon Snow",
          age: 26,
          address: "Ottawa No. 2 Lake Park"
        }
      ]
    };
  },
  methods: {
    Search() {
      this.getQueryData(1, 10, 1, this.value).then(res => {
        if (res.code === 0) {
          this.$Message.success("搜索成功");
          this.data6 = res.data.list;
        } else {
          this.$Message.error("查询失败");
        }
      });
    },
    show(val) {
      this.defaultList = [];
      this.Title = "编辑";
      this.OnText = "编辑";
      this.modal1 = true;
      this.isStatus = false;
      this.isShowPaawd = false;
      this.formValidate.mobile = val.mobile;
      if (val.avatar) {
        this.defaultList.push(val.avatar);
        this.UploadPicture = val.avatar;
      } else {
        this.defaultList = [];
      }
      this.formValidate.realName = val.realName;
      this.model10 = val.role;
      this.ChangeValId = val._id;
    },
    remove(val) {
      this.$Modal.confirm({
        title: "是否删除",
        // content: "<p>Content of dialog</p><p>Content of dialog</p>",
        onOk: () => {
          deleteUser(val.row._id).then(res => {
            if (res.data.code === 0) {
              this.$Message.info("删除成功");
              this.getQueryData(1, 10, 1).then(response => {
                this.data6 = response.data.list;
              });
            } else {
              this.$Message.error("删除失败");
            }
          });
        },
        onCancel: () => {
          this.$Message.info("取消");
        }
      });
    },
    getShowData() {
      this.cityList = [];
      QueryRole(1, 10, 1).then(res => {
        let newres = res.data.data.list;
        for (let i = 0; i < newres.length; i++) {
          let info = {};
          info.value = newres[i]._id;
          info.label = newres[i].access;
          this.cityList.push(info);
        }
      });
    },
    addUser() {
      this.modal1 = true;
      this.OnText = "添加";
      this.isStatus = true;
      this.isShowPaawd = true;
      this.model10 = [];
      this.defaultList = [];
      this.getShowData(); // 获取所有的角色的值
      this.$refs["formValidate"].resetFields();
    },
    ok() {
      this.$refs["formValidate"].validate(valid => {
        if (valid) {
          if (this.UploadPicture) {
            addUserS(
              this.formValidate.mobile,
              this.formValidate.passwd,
              this.formValidate.realName,
              this.model10,
              this.UploadPicture
            ).then(res => {
              if (this.isStatus) {
                // 添加
                if (res.data.code === 0) {
                  this.$Message.success("Success!");
                  this.getQueryData(1, 10, 1).then(res => {
                    this.data6 = res.data.list;
                  });
                } else {
                  this.$Message.error("添加失败");
                }
              } else {
                // 编辑
                ChangeUser(
                  this.ChangeValId,
                  this.formValidate.mobile,
                  this.formValidate.realName,
                  this.model10,
                  this.UploadPicture
                ).then(response => {
                  if (response.data.code === 0) {
                    this.$Message.success("修改成功");
                    this.getQueryData().then(response1 => {
                      this.data6 = response1.data.list;
                    });
                  } else {
                    this.$Message.error("修改失败");
                  }
                });
              }
            });
          } else {
            this.$Message.info("请上传图片");
          }
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    getQueryData(page = "1", limi = "10", isShow = "1", search) {
      return new Promise((resolve, reject) => {
        queryUser(page, limi, isShow, search)
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    OnChange(val) {
      this.getQueryData(val, 10, 1).then(res => {
        if (res.code === 0) {
          this.data6 = res.data.list;
        } else {
          this.$Message.error("查询数据失败");
        }
      });
    },
    ChangePassword(val) {
      this.modalPwd = true;
      this.$refs["formValidatePwd"].resetFields();
    },
    ResetPassword() {
      ChangeUserPwd(
        this.formValidatePwd.oldPassword,
        this.formValidatePwd.password
      ).then(res => {
        if (res.data.code === 0) {
          this.$Message.success("修改成功");
        } else {
          this.$Message.error("修改失败");
        }
      });
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file) {
      if (this.defaultList.length != 0) {
        removeImage(this.UploadPicture.pId).then(res => {
          // this.$Message.success(fileName + "删除成功");
        });
      }
      this.defaultList = [];
      this.UploadPicture.name = res.data.filename;
      this.UploadPicture.url = res.data.url;
      this.UploadPicture.pId = res.data._id;
      let Aray = { name: res.data.filename, url: res.data.url };
      this.defaultList.push(Aray);
      this.$Message.success(res.data.filename + "图片上传成功");
      // file.url =
      //   "https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar";
      // file.name = "7eb99afb9d5f317c912f08b5212fd69a";
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "The file format is incorrect",
        desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "Exceeding file size limit",
        desc: "File  " + file.name + " is too large, no more than 2M."
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Notice.warning({
          title: "Up to five pictures can be uploaded."
        });
      }
      return check;
    },
    onRemove(file, fileList) {
      let fileId = "";
      let fileName = "";
      if (file.pId) {
        fileId = file.pId;
        fileName = file.name;
      } else {
        fileId = file.response.data._id;
        fileName = file.response.data.filename;
      }
      removeImage(fileId).then(res => {
        this.$Message.success(fileName + "删除成功");
      });
    }
  },
  created() {
    this.getShowData(); // 获取所有的角色的值
    this.getQueryData().then(res => {
      this.data6 = res.data.list;
      if (res.data.count >= 10) {
        this.isShow = true;
      }
    });
  }
};
</script>
<style scope lang="scss">
</style>
